<template>
  <el-upload
    ref="upload"
    :action="actionApi"
    :show-file-list="false"
    name="file"
    :on-exceed="handleExceed"
    :auto-upload="auto"
    :headers="{ authorization: token, 'Request-from': RequestFrom }"
    v-bind="$attrs"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :limit="1"
  >
    <template v-for="(index, name) in $slots" v-slot:[name]>
      <slot :name="name"></slot>
    </template>
    <div v-if="file">
      {{ filename }}
    </div>
    <div v-else>
      <div class="flex items-center justify-center w-24 h-12 text-[14px] border border-blue-100 border-dashed rounded">
        <div>点击上传文件</div>
      </div>
      <Prompt :text="'文件类型仅支持' + fileExtensions" />
    </div>
  </el-upload>
</template>

<script setup lang="ts">
import { watch } from 'vue'
import { uploadFile } from '@/composables/useUpload'
const props = defineProps({
  action: {
    type: String,
    default: '/upload/file'
  },
  auto: {
    type: Boolean,
    default: true
  },
  imageClass: {
    type: String,
    default: ''
  }
})

// 定义文件 v-model
const fileModel = defineModel({
  type: String,
  default: '',
  required: true
})

const { upload, actionApi, beforeUpload, handleExceed, handleSuccess, file, token, RequestFrom, filename, fileExtensions } = uploadFile(props.action)
// 更新 model 的 value
watch(
  () => file.value,
  (newValue, oldValue) => {
    fileModel.value = newValue
  }
)
</script>
